<?php
/**
 * 代码原链接 https://mp.weixin.qq.com/s?__biz=MzIxODQyNTU1MA==&amp;mid=2247484170&amp;idx=1&amp;sn=13f52977efa519ff1a02dd023dd879ef&amp;chksm=97ebf2aba09c7bbd2a1b3677c841e375176ff956fc96c4fc4e9fb836092148493da188941ef3&amp;scene=27&key=&ascene=1&uin=&devicetype=iMac+MacBookPro15%2C2+OSX+OSX+12.2.1+build(21D62)&version=13080712&nettype=WIFI&lang=zh_CN&countrycode=CN&fontScale=100
 */
class Originator
{
    private $state;
    public function SetMeneto(Memento $m)
    {
        $this->state = $m->GetState();
    }
    public function CreateMemento()
    {
        $m = new Memento();
        $m->SetState($this->state);
        return $m;
    }

    public function SetState($state)
    {
        $this->state = $state;
    }

    public function ShowState()
    {
        echo $this->state, PHP_EOL;
    }
}

class Memento
{
    private $state;
    public function SetState($state)
    {
        $this->state = $state;
    }
    public function GetState()
    {
        return $this->state;
    }
}

class Caretaker
{
    private $memento;
    public function SetMemento($memento)
    {
        $this->memento = $memento;
    }
    public function GetMemento()
    {
        return $this->memento;
    }
}

$o = new Originator();
$o->SetState('状态1');
$o->ShowState();

// 保存状态
$c = new Caretaker();
$c->SetMemento($o->CreateMemento());

$o->SetState('状态2');
$o->ShowState();

// 还原状态
$o->SetMeneto($c->GetMemento());
$o->ShowState();